/*
 * Copyright (c) 2006-2020, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2020-08-07     lyh       the first version
 */
#include <rtthread.h>
#include <paho_mqtt.h>

/**
 * mqtt 常用信息设置
 */
#define MQTT_URI                "tcp://ngrok2.xiaomiqiu.cn:883" //mqtt服务器uri地址
#define MQTT_USERNAME           "admin" // mqtt服务器用户名
#define MQTT_PASSWORD           "admin" // mqtt 服务器密码
#define MQTT_SUBTOPIC           "mqtt"  // mqtt 服务器订阅主题
#define MQTT_PUBTOPIC           "mqtt"  // mqtt 服务器发布主题

/* define MQTT client context */
static MQTTClient client;

/* mqtt连接回调函数 */
void mymqtt_connect_callback()
{
    rt_kprintf("connect success --- \n");
}
/* mqtt连接成功回调函数 */
void mymqtt_online_callback()
{
    rt_kprintf("online ----- \n");
}
/* mqtt订阅回调函数 */
void mymqtt_sub_callback()
{
    rt_kprintf("sub callback \n");
}

/* mqtt主入口函数 */
void mqtt_main()
{

    /* init condata param by using MQTTPacket_connectData_initializer */
    MQTTPacket_connectData condata = MQTTPacket_connectData_initializer;

    client.uri = MQTT_URI;
    client.isconnected = 0;
    /* 分配内存 */
    memcpy(&client.condata, &condata, sizeof(condata));

    client.condata.clientID.cstring = "test";
    client.condata.keepAliveInterval = 60;
    client.condata.cleansession = 1;
    client.condata.username.cstring = MQTT_USERNAME;
    client.condata.password.cstring = MQTT_PASSWORD;

    client.condata.will.topicName.cstring = MQTT_PUBTOPIC;     //设置推送主题

    /* 分配缓冲区 */
    client.buf_size = client.readbuf_size = 1024;
    client.buf = rt_calloc(1, client.buf_size);
    client.readbuf = rt_calloc(1, client.readbuf_size);
    if (!(client.buf && client.readbuf))
    {
        rt_kprintf("no memory for MQTT client buffer! \n");
    }

    /* 设置回调函数 */
    client.connect_callback = mymqtt_connect_callback;
    client.online_callback = mymqtt_online_callback;         //设置上线回调函数

    /* 启动连接 */
    paho_mqtt_start(&client);


}
/* mqtt发布消息函数 */
void mymqtt_pub(char *msg)
{
    const char *msg_str = msg;
    paho_mqtt_publish(&client, QOS1, MQTT_PUBTOPIC, msg_str);
}
MSH_CMD_EXPORT(mqtt_main, mymqtt);
MSH_CMD_EXPORT(mymqtt_pub, mymqtt_pub);
